package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /*@Autowired
    private HttpServletRequest request;*/


    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody Employee employee){
        //①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //②. 根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(wapper);
        if(one == null){ //代表用户没有查询到
            //③. 如果没有查询到, 则返回登录失败结果
            return R.error("没有此用户");
        }
        //④. 密码比对，如果不一致, 则返回登录失败结果
        if(!password.equals(one.getPassword())){
            return R.error("密码错误");
        }
        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(one.getStatus() == 0){
            return R.error("此员工已禁用");
        }
        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        HttpSession session = request.getSession();
        session.setAttribute("employee",one.getId());
        return R.success(one);
    }


    @PostMapping("/logout")
    public R logOut(HttpServletRequest request){
        //1.清空用户的session信息可以
        HttpSession session = request.getSession();
        //2.清空employee
        session.setAttribute("employee",null);
        return R.success("退出成功");
    }

    /**
     * RequestBody 请求的json 转换位java对象
     * @param employee
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee,HttpServletRequest request){
        //1.查看下用户是否存在
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(wapper);
        if(one !=null){
            return R.error("添加失败,用户已存在");
        }
        //如果用户名相同 ，出现 SQLIntegrityConstraintViolationException
        //用户密码， 设置初始密码123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        //添加到数据库即可
        employeeService.save(employee);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R findByPage(Integer page,Integer pageSize ,String name){
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        if(name != null){
            //根据名字来进行一个条件查询
            wapper.like(Employee::getName,name);
        }
        //page1 包含前端页面锁需要的两个属性
        Page<Employee> page1 = employeeService.page(pageInfo, wapper);
        //在使用plus 分分页功能，配置分页插件
        return R.success(page1);
    }


    /**
     * 启用或者禁用用户
     * Long 类型 长度过长，会出现精度丢失
     */
    @PutMapping//
    public R update(@RequestBody Employee employee,HttpServletRequest request){
        //1.根据用户的id 修改状态。
        //1.1 查询出这个用户
        if(employee.getId() == 1){
            return R.success("该用户不能被禁用");
        }
        Employee emp = employeeService.getById(employee.getId());
        if(emp == null){
            //代表不存储
            return R.error("用户不存在");
        }
        //更新状态
        //employee.setStatus(employee.getStatus());  增加KPI
        //更新修改的时间
        employee.setUpdateTime(LocalDateTime.now());
        //更新修改人 -- 动态
        HttpSession session = request.getSession();
        Long empId = (Long) session.getAttribute("employee");
        //如果登录的id 和 用户修改的id不是同一个人，并且不是管理员，那么就不允许修改
        //Long == 比较出现了问题.
        if(empId.longValue() == employee.getId().longValue() || empId.longValue() == 1l){
            //2.修改数据库
            return R.success("修改状态成功");
        }else {
            return R.error("权限不足");
        }
    }


    /**
     * 根据id 查询  回显数据
     *  @PathVariable 代表需要从请求URL获取参数
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){

        if(id == null){
            return R.error("参数非法");
        }
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}